<template>
  <div class="contentView" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="routeHeader">
      <el-button
        class="mr-5px"
        v-if="formType != 'view'"
        @click="submitForm(1)"
        type="primary"
        :disabled="formLoading"
        v-hasPermi="['quality:maintain-internal-relation:save']"
        >保 存</el-button
      >
      <el-button
        class="mr-5px"
        v-if="formType != 'view'"
        @click="submitForm(2)"
        type="primary"
        :disabled="formLoading"
        v-hasPermi="['quality:maintain-internal-relation:submit']"
        >提 交</el-button
      >
      <el-button @click="goBack">关 闭</el-button>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 63}px`">
      <div class="orderTitle">
        <img src="@/assets/imgs/hasColorLogo.png" />
        内部工作联系单
      </div>
      <el-row class="orderView" v-loading="formLoading">
        <el-col :span="24" class="detailTitle">基本信息</el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">订单号<span style="color: red">*</span></span>
          <el-input
            class="rightIpt"
            v-model="formData.orderNumber"
            placeholder="请输入"
            @keyup.enter="searchOrder"
            v-loading="orderLoading"
            :disabled="formType == 'view'"
          />
        </el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">产品编号<span style="color: red">*</span></span>
          <el-select
            v-model="formData.productNumber"
            placeholder="请选择产品编号"
            filterable
            remote
            reserve-keyword
            :remote-method="getproductNumberList"
            :loading="productNumberLoading"
            class="!w-220px"
            @change="changeProductNumber"
            :disabled="formType == 'view'"
          >
            <el-option
              v-for="dict in productNumberList"
              :key="dict.productNumber"
              :label="dict.productNumber"
              :value="dict.productNumber"
            />
          </el-select>
        </el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">产品名称</span>
          <el-input class="rightIpt" v-model="formData.productName" disabled />
        </el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">产品规格</span>
          <el-input class="rightIpt" v-model="formData.productStandard" disabled />
        </el-col>
        <el-col :span="6" class="detailItem" style="border-left: none">
          <span class="leftLabel">联系类型<span style="color: red">*</span></span>
          <el-select
            v-model="formData.dictRelationType"
            placeholder="请选择联系类型"
            class="rightIpt"
            @change="changeDictRelationType"
            :disabled="formType == 'view'"
          >
            <el-option
              v-for="dict in getIntDictOptions('internal_relation_type')"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">客户代码</span>
          <el-input class="rightIpt" v-model="formData.customerCode" disabled />
        </el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">客户名称</span>
          <el-input class="rightIpt" v-model="formData.customerName" disabled />
        </el-col>
        <el-col :span="6" class="detailItem">
          <span class="leftLabel">联系单号</span>
          <el-input class="rightIpt" v-model="formData.relationOrderNumber" disabled />
        </el-col>
        <el-col :span="24" class="detailTitle">联系内容</el-col>
        <!-- 其他支撑 -->
        <el-input
          v-show="formData.dictRelationType != 20"
          :disabled="formType == 'view'"
          resize="none"
          v-model="formData.relationContent"
          :rows="6"
          type="textarea"
        />
        <!-- 仓库支撑 -->
        <el-table
          ref="singleTableRef"
          :data="formData.childList"
          style="width: 100%"
          border
          class="tableView"
          v-show="formData.dictRelationType == 20"
        >
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column
            v-for="item in tableTitle"
            :key="item.val"
            :prop="item.val"
            :label="item.label"
            min-width="200"
            align="left"
          >
            <template #default="scope">
              <div v-if="['productNumber'].includes(item.val)" class="searchIpt">
                <el-select
                  v-model="scope.row[item.val]"
                  placeholder=""
                  filterable
                  remote
                  :remote-method="componentSearch"
                  @change="
                    (e) => {
                      handleChangePd(scope.row, e)
                    }
                  "
                  :disabled="formType == 'view'"
                >
                  <el-option
                    v-for="channel in componentList"
                    :key="channel.productNumber"
                    :value="channel.productNumber"
                    :label="channel.productNumber"
                  />
                </el-select>
                <Icon
                  icon="ep:search"
                  v-if="formType != 'view'"
                  class="search-icon"
                  @click="handleSearch(scope)"
                />
              </div>
              <el-input
                v-else-if="['quantity', 'remark'].includes(item.val)"
                v-nextInput="item.val"
                :name="item.val"
                v-model="scope.row[item.val]"
                class="tableIpt"
                :disabled="formType == 'view'"
              />
              <template v-else>{{ scope.row[item.val] }}</template>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="left" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                link
                type="primary"
                @click="addCol"
                v-show="scope.$index == formData.childList.length - 1"
                :disabled="formType == 'view'"
                >新增行</el-button
              >
              <el-button
                size="small"
                link
                type="danger"
                @click="delTableCol(scope.$index)"
                v-if="scope.$index != 0"
                :disabled="formType == 'view'"
                >移除行</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-scrollbar>
    <!-- 产品编号 -->
    <CustomerProfile ref="componentRef" @success="addData" />
  </div>
</template>
<script setup lang="ts">
   import { getIntDictOptions } from '@/utils/dict'
   import * as MaintainInternalRelationApi from '@/api/quality/maintenanceManagement/maintainInternalRelation'
   import * as productRelationApi from '@/api/orderManagement/productRelation'
   import { useTagsViewStore } from '@/store/modules/tagsView'

   import CustomerProfile from '@/views/orderManagement/marketing/productRelation/customerProfile.vue'
   const message = useMessage() // 消息弹窗

   const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
   const formType = ref('') // 表单的类型：create - 新增；update - 修改  view - 查看
   const formData = ref({
     internalRelationId: undefined,
     orderNumber: undefined,
     productNumber: undefined,
     productName: undefined,
     partSpecification: undefined,
     dictRelationType: undefined,
     customerCode: undefined,
     customerName: undefined,
     relationOrderNumber: undefined,
     childList: [], //联系内容
     relationContent: undefined //文字联系内容
   })
   const formRef = ref() // 表单 Ref

   //搜索订单号
   const orderLoading = ref(false)
   const searchOrder = async () => {
     orderLoading.value = true
     let params = {
       orderNumber: formData.value.orderNumber,
       productNumber: null
     }
     const data = await MaintainInternalRelationApi.getMaintainInternalRelationDetailOrderDetail(
       params
     )
     orderLoading.value = false
     if (!data.length) {
       message.error('订单号不存在！')
       return
     }
     if (data.length == 1) {
       formData.value.productNumber = data[0].productNumber
       formData.value.productName = data[0].productName
       formData.value.productStandard = data[0].productStandard
       formData.value.customerCode = data[0].customerCode
       formData.value.customerName = data[0].customerName
     }
     productNumberList.value = data
   }

   /**产品编号搜索 */
   const productNumberList = ref([])
   const productNumberLoading = ref(false)
   const getproductNumberList = async (val: string) => {
     productNumberLoading.value = true
     let params = {
       orderNumber: formData.value.orderNumber,
       productNumber: val || formData.value.productNumber
     }
     const data = await MaintainInternalRelationApi.getMaintainInternalRelationDetailOrderDetail(
       params
     )
     productNumberLoading.value = false
     productNumberList.value = data
   }
   /**产品编号选择 */
   const changeProductNumber = (val) => {
     const data = productNumberList.value.filter((item) => item.productNumber == val)[0]
     formData.value.productName = data.productName
     formData.value.productStandard = data.productStandard
     formData.value.customerCode = data.customerCode
     formData.value.customerName = data.customerName
   }
   /**选择类型改变
    * 20:仓库支撑
    */
   const changeDictRelationType = (val: number) => {
     //仓库支撑
     if (val == 20) {
       formData.value.relationContent = ''
       addCol()
     } else {
       formData.value.childList = []
     }
   }
   /**部件搜索 */
   const componentList = ref([])
   const componentSearch = async (productNumber: string) => {
     const data = await productRelationApi.getProductsList({ productNumber })
     componentList.value = data.list
   }
   //打开部件弹框
   const componentRef = ref()
   const handleSearch = async (data: object) => {
     componentRef.value.open(data.$index, data.row.productNumber)
   }
   //部件弹框选中
   const addData = async (data) => {
     console.log(data)
     formData.value.childList[data.index.value].productNumber = data.list[0].productNumber
     formData.value.childList[data.index.value].productName = data.list[0].productName
     formData.value.childList[data.index.value].productStandard = data.list[0].productStandard
     formData.value.childList[data.index.value].partUnit = data.list[0].partUnit
   }
   /**部件选择切换 */
   const handleChangePd = (data, e) => {
     const res = componentList.value.filter((item) => item.productNumber == e)[0]
     data.productName = res.productName
     data.productStandard = res.productStandard
     data.partUnit = res.partUnit
   }
   /** 提交表单
    * type 1 - 保存 ) 2 - 提交
    */
   const roleList = ref([null, undefined, ''])
   const submitForm = async (type: number) => {
     let data = JSON.parse(JSON.stringify(formData.value))
     data.submitFlag = type
     //提交，进入校验
     if (type == 2) {
       if (roleList.value.includes(data.orderNumber)) {
         message.error('请输入订单号')
         return
       }
       if (roleList.value.includes(data.productNumber)) {
         message.error('请产品编号')
         return
       }
       if (roleList.value.includes(data.dictRelationType)) {
         message.error('请选择联系类型')
         return
       }
       if (data.dictRelationType != 20 && roleList.value.includes(data.relationContent)) {
         message.error('联系内容不能为空')
         return
       }
       //如果是仓库支撑
       if (data.dictRelationType == 20) {
         let flag = false
         data.childList.map((item) => {
           if (roleList.value.includes(item.productNumber)) {
             flag = true
           }
         })
         if (flag) {
           message.error('部件编号不能为空')
           return
         }
         const newArr = data.childList.map((item) => item.productNumber)
         const isRepeat = newArr.some((item, index, arr) => arr.indexOf(item) != index)
         if (isRepeat) {
           message.error('部件编号不能重复')
           return
         }
       }
     }
     console.log(data)
     formLoading.value = true
     try {
       await MaintainInternalRelationApi.updateMaintainInternalRelation(data)
       let str = type == 1 ? '保存成功' : '提交成功'
       message.success(str)
       goBack()
     } finally {
       formLoading.value = false
     }
   }

   const tableTitle = ref([
     {
       label: '部件编号',
       val: 'productNumber'
     },
     {
       label: '部件名称',
       val: 'productName'
     },
     {
       label: '数量',
       val: 'quantity'
     },
     {
       label: '产品规格',
       val: 'productStandard'
     },
     {
       label: '单位',
       val: 'partUnit'
     },
     {
       label: '备注',
       val: 'remark'
     }
   ])
   /**新增行 */
   const addCol = () => {
     formData.value.childList.push({
       productNumber: undefined,
       productName: undefined,
       quantity: undefined,
       productStandard: undefined,
       partUnit: undefined,
       remark: undefined
     })
   }
   /**移除行 */
   const delTableCol = (index: number) => {
     formData.value.childList.splice(index, 1)
   }

   /**返回 */
   const tagsViewStore = useTagsViewStore()
   const route = useRouter() // 路由
   const goBack = async () => {
     //获取当前路由并删除tagView
     tagsViewStore.delView(route.currentRoute.value)
     //跳转列表页
     route.push({
       path: '/quality/quality/maintenanceManagement/maintainInternalRelation'
     })
   }

   /** 重置数据 */
   const resetForm = () => {
     formData.value = {
       internalRelationId: undefined,
       orderNumber: undefined,
       productNumber: undefined,
       productName: undefined,
       partSpecification: undefined,
       dictRelationType: undefined,
       customerCode: undefined,
       customerName: undefined,
       relationOrderNumber: undefined,
       childList: [],
       relationContent: undefined
     }
     formRef.value?.resetFields()
   }
   // 获得id
   const { query } = useRoute() // 路由的查
   const contentHeight = ref(0)
   /** 初始化 */
   onMounted(async () => {
     formLoading.value = true
     await resetForm()
     if (query.id) {
       formData.value = await MaintainInternalRelationApi.getMaintainInternalRelation(query.id)
     }
     formType.value = query.type
     contentHeight.value = document.body.clientHeight - 127
     formLoading.value = false
   })
</script>
<style lang="scss" scoped>
   .contentView {
     padding: 10px;
     background: #fff;
     .orderTitle {
       width: 100%;
       line-height: 53px;
       position: relative;
       text-align: center;
       font-size: 30px;
       img {
         width: 232px;
         height: 53px;
         position: absolute;
         left: 0;
         top: 0;
       }
     }
   }
   .routeHeader {
     width: 100%;
     border-bottom: 1px solid #969696;
     display: flex;
     align-items: center;
     padding: 10px 0;
   }
   .tableView {
     :deep(th) {
       background: rgb(233, 251, 251) !important;
     }
     .searchIpt {
       position: relative;
       .search-icon {
         position: absolute;
         right: 10px;
         top: calc(50% - 8px);
         cursor: pointer;
       }
     }
   }
   .orderView {
     border: 1px solid #000;
     font-size: 14px;
     border-color: #000;
     :deep(.el-input__wrapper) {
       box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
       cursor: default;
       .el-input__inner {
         cursor: default !important;
       }
     }
     .detailTitle {
       background: rgb(179, 255, 255);
       font-weight: bold;

       line-height: 30px;
       padding-left: 10px;
       border-bottom: 1px solid #000;
     }
     .detailItem {
       line-height: 30px;
       display: flex;
       align-items: center;
       border-bottom: 1px solid #000;
       .leftLabel {
         width: 110px;
         flex-shrink: 0;
         text-align: center;
         border-right: 1px solid #000;
         background: rgb(233, 251, 251);
       }
       .rightIpt {
         flex: 1;
         :deep(.is-focus) {
           border: none !important;
         }
       }
     }
     .detailItem + .detailItem {
       border-left: 1px solid #000;
     }
   }
</style>